//
//  MLHomeViewController.m
//  keJiNews
//
//  Created by 魔龙 on 16/4/12.
//  Copyright © 2016年 魔龙. All rights reserved.
//

#import "MLHomeViewController.h"
#import "MLTitleLable.h"
#import "MLNewsTableViewController.h"
#import "UIView+Frame.h"
#import "masonry.h"

@interface MLHomeViewController ()<UIScrollViewDelegate>
/**
 *  标题栏
 */
@property (weak, nonatomic) IBOutlet UIScrollView *smallScrollView;
/**
 *  新闻内容栏
 */
@property (weak, nonatomic) IBOutlet UIScrollView *bigScrollView;
@property (nonatomic,assign) CGFloat beginOffsetX;
/**
 *  新闻接口的数组
 */
@property(nonatomic,strong) NSArray *arrayLists;
/**
 *  新闻控制器
 */
@property (nonatomic, strong) MLNewsTableViewController *newsScrollView;

@end

@implementation MLHomeViewController


#pragma mark - 页面首次加载
- (void)viewDidLoad {
    [super viewDidLoad];
    // 自动调整scrollview的 inset,设置为no
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.smallScrollView.showsHorizontalScrollIndicator = NO;
    self.smallScrollView.showsVerticalScrollIndicator = NO;
    self.smallScrollView.scrollsToTop = NO;
    self.bigScrollView.scrollsToTop = NO;
    self.bigScrollView.delegate = self;
    // 添加子控制器
    [self setupController];
    
    // 添加标题栏
    [self setupLable];
    
    // 子控制器ScrollView的大小
    CGFloat contentX = self.childViewControllers.count * [UIScreen mainScreen].bounds.size.width;
    self.bigScrollView.contentSize = CGSizeMake(contentX, 0);
    self.bigScrollView.pagingEnabled = YES;
    
    // 添加默认控制器到子控制器
    UIViewController *vc = [self.childViewControllers firstObject];
    vc.view.bounds = self.bigScrollView.bounds;
    [self.bigScrollView addSubview:vc.view];
    self.bigScrollView.showsHorizontalScrollIndicator = NO;
    
    // 设置标题栏一开始选择第一个
    MLTitleLable *lable = [self.smallScrollView.subviews firstObject];
    lable.scale = 1;

    self.newsScrollView = self.childViewControllers[0];
    self.newsScrollView.view.bounds = self.view.bounds;
    
        if (UIDevice.currentDevice.systemVersion.floatValue >= 8.0) {
            // 解决添加childViewControllers产生的偏移问题
            __weak typeof(self) weakSelf = self;
            [self.newsScrollView.view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(weakSelf.view.bounds.size);
                make.top.mas_offset(0);
            }];
        }
}



#pragma mark - 添加UI方法
/**
 *  添加子控制器
 */
- (void)setupController{
    for (int i = 0; i < self.arrayLists.count; i++) {
        // 从NewsStroyboard创建子控制器
        MLNewsTableViewController *tvc = [[UIStoryboard storyboardWithName:@"News" bundle:[NSBundle mainBundle]] instantiateInitialViewController];
        tvc.title = self.arrayLists[i][@"title"];
        tvc.urlString =self.arrayLists[i][@"urlString"];
        [self addChildViewController:tvc];
    }
}

/**
 *  添加标题栏
 */
- (void)setupLable{
    for (int i = 0; i < self.arrayLists.count; i++) {
        CGFloat lblW = 70;
        CGFloat lblH = 40;
        CGFloat lblY = 0;
        CGFloat lblX = i * lblW; //i * lblW
        MLTitleLable *lbl = [[MLTitleLable alloc] init];
        // 从子控制器得到标题名字
        MLHomeViewController *hvc = self.childViewControllers[i];
        lbl.text = hvc.title;
        lbl.frame = CGRectMake(lblX, lblY, lblW, lblH);
        lbl.font = [UIFont systemFontOfSize:19];
        [self.smallScrollView addSubview:lbl];
        lbl.tag = i;
        lbl.userInteractionEnabled = YES;
        [lbl addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(lblClick:)]];
    }
    // 修改smallScrollView的CGSize
    self.smallScrollView.contentSize = CGSizeMake(70 * self.arrayLists.count, 0);
}

#pragma mark - 点击事件
/**
 *  标题栏label的点击事件
 */
- (void)lblClick:(UITapGestureRecognizer *)recognizer{
    MLTitleLable *titleLable = (MLTitleLable *)recognizer.view;
    CGFloat offsetX = titleLable.tag * self.bigScrollView.frame.size.width;
    CGFloat offsetY = self.bigScrollView.contentOffset.y;
    CGPoint offset = CGPointMake(offsetX, offsetY);
    
    [self.bigScrollView setContentOffset:offset animated:YES];
    
    // 子控制器切换
    [self setNewsScrollViewWithTableViewIndex:titleLable.tag];
}

- (void)rightItemClick{
}

#pragma mark - 子控制器NewsScrollView
/**
 *  子控制器切换
 */
- (void)setNewsScrollViewWithTableViewIndex:(NSInteger)index
{
    self.newsScrollView.tableView.scrollsToTop = NO;
    self.newsScrollView = self.childViewControllers[index];
    self.newsScrollView.tableView.scrollsToTop = YES;
}

#pragma mark - scrollView代理方法
/**
 *  滚动结束后调用（代码导致）
 */
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    // 获得索引
    NSUInteger index = scrollView.contentOffset.x / self.bigScrollView.frame.size.width;
    
//    // 滚动标题栏
//    MLTitleLable *titleLable = (MLTitleLable *)self.smallScrollView.subviews[index];
//    
//    CGFloat offsetx = titleLable.center.x - self.smallScrollView.frame.size.width * 0.5;
//    
//    CGFloat offsetMax = self.smallScrollView.contentSize.width - self.smallScrollView.frame.size.width;
//    if (offsetx < 0) {
//        offsetx = 0;
//    }else if (offsetx > offsetMax){
//        offsetx = offsetMax;
//    }
//    
//    CGPoint offset = CGPointMake(offsetx, self.smallScrollView.contentOffset.y);
//    [self.smallScrollView setContentOffset:offset animated:YES];
    
    // 添加控制器
    MLNewsTableViewController *newsVc = self.childViewControllers[index];
    newsVc.index = index;
    
    [self.smallScrollView.subviews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if (idx != index) {
            MLTitleLable *temlabel = self.smallScrollView.subviews[idx];
            temlabel.scale = 0.0;
        }
    }];
    
    // 子控制器切换
    [self setNewsScrollViewWithTableViewIndex:index];
    
    if (newsVc.view.superview) return;
    
    newsVc.view.frame = scrollView.bounds;
    [self.bigScrollView addSubview:newsVc.view];
}

/**
 *  滚动结束（手势导致）
 */
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [self scrollViewDidEndScrollingAnimation:scrollView];
}

/**
 *  正在滚动
 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    // 取出绝对值 避免最左边往右拉时形变超过1
    CGFloat value = ABS(scrollView.contentOffset.x / scrollView.frame.size.width);
    NSUInteger leftIndex = (int)value;
    NSUInteger rightIndex = leftIndex + 1;
    CGFloat scaleRight = value - leftIndex;
    CGFloat scaleLeft = 1 - scaleRight;
    MLTitleLable *labelLeft = self.smallScrollView.subviews[leftIndex];
    labelLeft.scale = scaleLeft;
    // 考虑到最后一个板块，如果右边已经没有板块了 就不在下面赋值scale了
    if (rightIndex < self.smallScrollView.subviews.count) {
        MLTitleLable *labelRight = self.smallScrollView.subviews[rightIndex];
        labelRight.scale = scaleRight;
    }

}

#pragma mark - 懒加载
- (NSArray *)arrayLists{
    if (_arrayLists == nil) {
        _arrayLists = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"NewsURLs.plist" ofType:nil]];
    }
    return _arrayLists;
}



@end
